﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.IO;

namespace Magellan.ProjectWizards.Framework
{
    public class ProjectGenerator
    {
        private readonly string _template;
        private readonly string _rootDirectory;
        private readonly Dictionary<string, string> _replacements;

        public ProjectGenerator(string template, string rootDirectory, Dictionary<string, string> replacements)
        {
            _template = template;
            _rootDirectory = rootDirectory;
            _replacements = replacements;
        }

        public void RenderFile(string path, string outputPath)
        {
            var resourcePath = path.Replace("\\", ".").Replace("/", ".");
            resourcePath = "Magellan.ProjectWizards." + _template + "." + resourcePath;

            var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourcePath);
            if (resourceStream == null)
            {
                throw new Exception(string.Format("A resource with the path {0} could not be found", resourcePath));
            }

            using (var reader = new StreamReader(resourceStream))
            {
                var streamContents = reader.ReadToEnd();
                streamContents = ApplyReplacements(streamContents);

                outputPath = ApplyReplacements(outputPath);
                outputPath = Path.GetFullPath(Path.Combine(_rootDirectory, outputPath));
                Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
                File.WriteAllText(outputPath, streamContents);
            }
        }

        private string ApplyReplacements(string input)
        {
            foreach (var replacement in _replacements)
            {
                input = input.Replace(replacement.Key, replacement.Value);
            }
            return input;
        }
    }
}
